package com.aote.plugins.json;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonCompare {

	private static Logger log = Logger.getLogger(JsonCompare.class);
	
	public static boolean hasKey(JSONObject jo, String attr) {
		return jo.has(attr);
	}

	public static JSONObject findDiff(JSONObject jo1, JSONObject jo2) {
		log.debug("findDiff:");
		log.debug("参数1:" + jo1);
		log.debug("参数2:" + jo2);
		// JSONObject jsonobject = null;
		Set<String> keySet1 = jo1.keySet();
		// jsonobject = new JSONObject();
		JSONObject jo = new JSONObject();
		for (String s : keySet1) {
			if (!(jo1.get(s).equals(jo2.get(s))) && !jo1.get(s).equals("")
					&& !jo1.isNull(s)) {
				jo2.put(s, jo1.get(s));
				// jo.put("field", s);
				// jo.put("newVal", jo1.get(s));
				// jo.put("oldVal", jo2.get(s));
				// jsonArray.put(jo);
			}
		}
		log.debug("返回:" + jo);
		return jo2;
	}
	//这个方法是将json转换成HashMap<String, Object> 
	 static HashMap<String, Object> toHashMap(JSONObject object)  
	   {  
	       HashMap<String, Object> data = new HashMap<String, Object>();  
	       // 将json字符串转换成jsonObject  
	       Iterator it = object.keys();  
	       // 遍历jsonObject数据，添加到Map对象  
	       while (it.hasNext())  
	       {  
	           String key = String.valueOf(it.next());  
	           if(object.isNull(key))
	        	   data.put(key,  null);
	           else {
	           Object value =  object.get(key);  
	           data.put(key, value); 
	           }
	       }  
	       return data;  
	   } 
	 
	 public static JSONObject removeNulls(JSONObject obj) {
		 String[] keys = new String[obj.length()];
		 Iterator<String> itr = obj.keys();
		 int i = 0;
		 while(itr.hasNext())
			 keys[i++] = itr.next();
		 
		 for(String key : keys) {
			 if(obj.isNull(key))
				 obj.remove(key);
		 }
		 return obj;
	 }
	 
	 public static JSONObject removeItem(JSONObject obj, String key) {
		 obj.remove(key);
		 return obj;
	 }
	 
	 public static JSONArray findDiff(JSONArray newMeters, JSONArray oldMeters, String f_tmp_userfile_id) {
		 JSONArray rows = new JSONArray();
		 for(int i=0; i<newMeters.length(); i++) {
			 JSONObject row = newMeters.getJSONObject(i);
			 row.put("f_tmp_userfile_id", f_tmp_userfile_id);
			 int n = findRowInArray(row, oldMeters);
			 //没找到
			 if(n == -1) {
				 rows.put(row);
				 row.remove("id");
			 } else {
				JSONObject row2 = oldMeters.getJSONObject(n);
				JSONObject rowx = compare(row, row2);
				rows.put(rowx);
				rowx.remove("id");
				oldMeters.remove(n); 
			 }
		 }
		 //删除的表
		 for(int i=0; i<oldMeters.length(); i++) {
			 JSONObject row = oldMeters.getJSONObject(i);
			 row.put("f_meter_flag", "删除");
			 row.put("f_tmp_userfile_id", f_tmp_userfile_id);
			 row.remove("id");
			 rows.put(row);
		 }
		 return rows;
	 }
	 
	 private static JSONObject compare(JSONObject row, JSONObject row2) {
		JSONObject rowx = new JSONObject();
		for(String key : row.keySet()) {
			if(row2.has(key)) {
				if(row.isNull(key)) {
				} else {
					if(!row2.get(key).equals(row.get(key))) {
						rowx.put(key, row.get(key));
					}
				}
			}
			else {
				if(!row.isNull(key))
					rowx.put(key, row.get(key));
			}
		}
		return rowx;
	}
	 
	private static int findRowInArray(JSONObject row, JSONArray oldMeters) {
		for(int i=0; i < oldMeters.length(); i++) {
			JSONObject obj = oldMeters.getJSONObject(i);
			if(obj.getString("id").equals(row.getString("id")))
				return i;
		}
		return -1;
	}
	public static JSONObject json(JSONObject obj1,JSONObject obj2)
		{
			 Map<String, Object> map1 =toHashMap(obj1);
			 Map<String, Object> map2 =toHashMap(obj2);
			
			 //得到后台传入的键值
			 List<String> m2key=new ArrayList();
		     for (Entry<String, Object> entry : map1.entrySet()) {  
		    	    m2key.add(entry.getKey());
		     } 
		    
		     for(int i=0;i<m2key.size();i++)
		     {
		    	 String key = m2key.get(i);
		    	 System.out.println(key);
		    	 Object value= map1.get(m2key.get(i));
		    	 Object value1= map2.get(m2key.get(i));
		    	 if(value==null){
		    		 map1.put(m2key.get(i),null);		 
		    	 }
		    	 else{
		    	 if(value.equals(value1))
		    	 {
		    		 map1.put(m2key.get(i),null);
		    	 }else
		    	 {
		    		 map1.put(m2key.get(i), value);
		    	 }
		     }}
		     JSONObject obj = new JSONObject(map1);
		     return obj;
		}
	/**
	 * 本函数为动态生成update语句
	 * 
	 * @author zhaotong
	 * @param tablename
	 *            表名
	 * @param obj
	 *            参数对象
	 * @param pobj
	 *            参数类型对象（调用时只需要将不是String类型的字段拼接传入即可）
	 * @return update 语句 不包括条件判断，条件可在业务逻辑中添加。
	 */
	public static String getUpdateSql(String tablename, JSONObject obj,
			JSONObject pobj) {
		String sql = "update " + tablename + " set ";
		List<String> list = new ArrayList();
		Map<String, Object> map = JSONPlugin.toHashMap(obj);
		Map<String, Object> map_type = JSONPlugin.toHashMap(pobj);
		for (Entry<String, Object> enty : map_type.entrySet()) {
			list.add(enty.getKey());
		}

		String sqlpart = "";
		for (Entry<String, Object> enty : map.entrySet()) {

			String str = "";
			if (list.contains(enty.getKey())) {
				if (map_type.get(enty.getKey()).equals("int")
						|| map_type.get(enty.getKey()).equals("float")
						|| map_type.get(enty.getKey()).equals("decimal")) {

					str = enty.getKey() + "=" + enty.getValue() + ",";
				}
				else if(map_type.get(enty.getKey()).equals("date"))
				{
					str=enty.getKey()+"=TO_DATE('"+enty.getValue()+"', 'yyyy-mm-dd hh24:mi:ss'),";
				}
				else {
					str = enty.getKey() + "='" + enty.getValue() + "',";

				}
			} else if (enty.getValue() == null) {
				str = enty.getKey() + "=" + enty.getValue() + ",";
			} else {

				str = enty.getKey() + "='" + enty.getValue() + "',";
			}
			sqlpart += str;

		}
		sqlpart = sqlpart.substring(0, sqlpart.length() - 1) + " ";
		return sql + sqlpart;

	}
	
	public static String getUserFilePartialUpdate(JSONObject obj) {
		String sql = "update t_userfiles set id = id";
		if(!obj.isNull("f_user_name")) 
			sql += ", f_user_name='" + obj.getString("f_user_name") + "'";
		if(!obj.isNull("f_user_phone")) 
			sql += ", f_user_phone='" + obj.getString("f_user_phone") + "'";
		if(!obj.isNull("f_subcompany")) 
			sql += ", f_subcompany='" + obj.getString("f_subcompany") + "'";
		if(!obj.isNull("f_last_check_date")) 
			sql += ", f_last_check_date='" + obj.getString("f_last_check_date") + "'";
		if(!obj.isNull("f_last_check_state")) 
			sql += ", f_last_check_state='" + obj.getString("f_last_check_state") + "'";
		if(!obj.isNull("f_checker")) 
			sql += ", f_checker='" + obj.getString("f_checker") + "'";
		if(!obj.isNull("f_checker_id")) 
			sql += ", f_checker_id='" + obj.getString("f_checker_id") + "'";
		if(!obj.isNull("f_archive_date")) 
			sql += ", f_archive_date='" + obj.getString("f_archive_date") + "'";
		if(!obj.isNull("f_user_type")) 
			sql += ", f_user_type='" + obj.getString("f_user_type") + "'";
		if(!obj.isNull("f_street")) 
			sql += ", f_street='" + obj.getString("f_street") + "'";
		if(!obj.isNull("f_residential_area")) 
			sql += ", f_residential_area='" + obj.getString("f_residential_area") + "'";
		if(!obj.isNull("f_building")) 
			sql += ", f_building='" + obj.getString("f_building") + "'";
		if(!obj.isNull("f_unit")) 
			sql += ", f_unit='" + obj.getString("f_unit") + "'";
		if(!obj.isNull("f_floor")) 
			sql += ", f_floor='" + obj.getString("f_floor") + "'";
		if(!obj.isNull("f_room")) 
			sql += ", f_room='" + obj.getString("f_room") + "'";
		if(!obj.isNull("f_address")) 
			sql += ", f_address='" + obj.getString("f_address") + "'";
		if(!obj.isNull("f_remark")) 
			sql += ", f_remark='" + obj.getString("f_remark") + "'";
		sql += " where id='" + obj.getString("f_userfile_id") + "'";
		return sql;
	}
	
	public static String getMeterFilePartialUpdate(JSONObject obj) {
		String sql = "update t_meterfiles set id = id";
		if(!obj.isNull("f_card_id")) 
			sql += ", f_card_id='" + obj.getString("f_card_id") + "'";
		if(!obj.isNull("f_meter_no")) 
			sql += ", f_meter_no='" + obj.getString("f_meter_no") + "'";
		if(!obj.isNull("f_meter_brand")) 
			sql += ", f_meter_brand='" + obj.getString("f_meter_brand") + "'";
		if(!obj.isNull("f_meter_measurement")) 
			sql += ", f_meter_measurement='" + obj.getString("f_meter_measurement") + "'";
		if(!obj.isNull("f_meter_diameter")) 
			sql += ", f_meter_diameter='" + obj.getString("f_meter_diameter") + "'";
		if(!obj.isNull("f_meter_reading")) 
			sql += ", f_meter_reading=" + obj.getInt("f_meter_reading") + "";
		if(!obj.isNull("f_meter_remain")) 
			sql += ", f_meter_remain=" + obj.getInt("f_meter_remain") + "";
		if(!obj.isNull("f_meter_total")) 
			sql += ", f_meter_total='" + obj.getString("f_meter_total") + "'";
		if(!obj.isNull("f_meter_accumulation")) 
			sql += ", f_meter_accumulation='" + obj.getString("f_meter_accumulation") + "'";
		if(!obj.isNull("f_remark")) 
			sql += ", f_remark='" + obj.getString("f_remark") + "'";
		sql += " where id='" + obj.getString("f_old_meter_id") + "'";
		return sql;
	}

	public static void main(String[] args) {
		JSONObject jo1 = new JSONObject(
				"{mobiles:'15249265120',content:'余额不足',f_user_name:'3',f_user_id:'2',senddate:'2016-10-29',operator:'1',name:1,id:'1'}");
		JSONObject jo2 = new JSONObject(
				"{mobiles:'15555555555',content:'余额不够',f_user_name:'3',f_user_id:'2',senddate:'2016-10-29',operator:'',name:'zhaotong',id:'2'}");
		JSONObject joo = JsonCompare.json(jo1, jo2);	
		System.out.println(joo);
	}

}
